package com.yuan.statemachine.core;

import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wjwei
 * 状态寄存器
 */
public class StateMachineRegistry<F extends Enum<F>, S extends Enum<S>, E extends Enum<E>> implements StateMachine<F, S, E> {
    public Map<Enum<F>, Set<StateEntry<F, S, E>>> stateEntryMap = new ConcurrentHashMap<>();


    @Override
    public StateResponseBody doAction(Enum<F> function, Enum<S> status, Enum<E> event, Object data) {
        Set<StateEntry<F, S, E>> entryList = stateEntryMap.get(function);
        for (StateEntry<F, S, E> stateEntry : entryList) {
            if (Objects.equals(stateEntry.getStatusEnum(), status)) {
                return stateEntry.getState().doEvent(event, data);
            }
        }
        return StateResponseBody.stateFail(StateResponseCode.NO_STATE);
    }

    @Override
    public void register(AbstractStateMachine<F, S, E> stateClass, Enum<S> statusEnum, Enum<F> functionEnum) {
        Set<StateEntry<F, S, E>> entryList = stateEntryMap.get(functionEnum);
        if (CollectionUtils.isEmpty(entryList)) {
            entryList = new HashSet<>();
        }
        StateEntry<F, S, E> entry = new StateEntry<>(stateClass, statusEnum);
        entryList.add(entry);
        stateEntryMap.put(functionEnum, entryList);
    }
}
